/**
 * websocket
 */
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';
import { getToken } from '@/utils/auth';
import store from '@/store';

let wsClient = null;
let timer = null;

/**
 * 初始化socket客户端并连接server
 */
export function initSocket() {
  // 根据https协议判断是否为ws或wss
  let proto = document.location.protocol == 'https:' ? 'wss:' : 'ws:';
  // 取地址+端口，配置80端口时port是空的，所以判断一下
  let address = document.location.port ? document.location.hostname + ':' + document.location.port : document.location.hostname;
  // 拼接请求地址(/websocket将被网关转发到message服务)
  const wsuri = proto + "//" + address + process.env.VUE_APP_WS_API + "/websocket/ws";

  let socket = new WebSocket(wsuri);

  wsClient = Stomp.over(socket);

  // 心跳（无效???还是断开）（websocket经nginx代理后，60s内没有交互则断开连接。）
  // wsClient.heartbeat.outgoing = 30000; // client will send heartbeats every 30000ms
  // wsClient.heartbeat.incoming = 30000;     // client receive heartbeats from the server every 30000ms

  // 生产环境关闭debug输出
  if(process.env.NODE_ENV === "production") {
    wsClient.debug = null;
  }

  let headers = {
    Authorization: 'Bearer ' + getToken() // token信息，并不是在gateway校验，在message服务中的websocket拦截器校验
  }

  wsClient.connect(headers, connectSuccess, connectError)
}

/**
 * websocket连接成功
 */
function connectSuccess(success) {
  console.warn('websocket连接成功...')
  console.warn(success)
  // 订阅消息
  subscribe()

  // 维护一个心跳
  timer = setInterval(() => {
    wsClient.send('ping')
  }, 30000)
}

/**
 * websocket连接失败
 */
function connectError(error) {
  console.error('websocket连接异常...')
  console.error(error)
  clearInterval(timer)
}

/**
 * 订阅消息
 */
function subscribe() {
  // 订阅公共频道 - 通知公告相关主题(/topic/notice)
  wsClient.subscribe(store.state.constants.ws_subscribe_pre_topic + store.state.constants.ws_subscribe_suf_notice, function (greeting) {
    // 处理消息
    refreshMsg(greeting.body)
  })

  // 订阅个人频道 - 业务相关主题(/user/${userName}/business)
  wsClient.subscribe(store.state.constants.ws_subscribe_pre_user + '/' + store.state.user.name + store.state.constants.ws_subscribe_suf_business, function (greeting) {
    // 处理消息
    refreshMsg(greeting.body)
  })
}

/**
 * 刷新消息
 */
function refreshMsg(msg) {
  if(msg) {
    if(store.state.user.wsMsg == msg) {
      store.commit('SET_WS_MSG', '');
      setTimeout(() => {
        store.commit('SET_WS_MSG', msg);
      })
    } else {
      store.commit('SET_WS_MSG', msg);
    }
  }
}
